<template>
  <div class="app-container">
    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="级别:" prop="alternativeCarLevelId">
          <el-select v-model="queryParams.alternativeCarLevelId" clearable>
            <template v-for="dict in levelList">
              <el-option :label="dict.level" :value="dict.id" :key="dict.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="状态:" prop="enableStatus">
          <el-select v-model="queryParams.enableStatus" clearable>
            <template v-for="dict in dict.type.enable_status">
              <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
      </el-col>
    </SearchContent>

    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">
        <el-button type="primary" size="mini" @click="handleAdd" v-hasPermi="['channel:carPricingStandard:add']">新增</el-button>
        <el-button type="primary" size="mini" @click="handleExport" v-hasPermi="['channel:carPricingStandard:export']">导出</el-button>
      </div>
      <div class="form-table">
        <el-table v-loading="loading" max-height="400" :data="dataList" :span-method="objectSpanMethod" style="width: 100%;margin: 0 auto;">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table :data="props.row.alternativeCarCityPricingList" border style="width: 100%" v-if="props.row.alternativeCarCityPricingList.length > 0">
                <el-table-column label="城市" align="center">
                  <template slot-scope="scope">
                    <span :class="{'blue':props.row.enableStatus ==1}">{{ scope.row.cityNames.toString() }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="维保替车费用(元)" align="center">
                  <template slot-scope="scope">
                    <span :class="{'blue':props.row.enableStatus ==1}">{{scope.row.alternativeCarFee}}</span>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center" prop="id">
            <template slot-scope="scope">
              <e-button :class="{'text':scope.row.enableStatus ==0}" v-hasPermi="['channel:carPricingStandard:edit']" size="mini" type="text" @click="handleUpdate(scope.row)" v-if="scope.row.enableStatus ==0">编辑</e-button>
              <el-button :class="{'text':scope.row.enableStatus ==0}" v-hasPermi="['channel:carPricingStandard:enable']" type="text" @click="start(scope.row)" v-if="scope.row.enableStatus ==0">启用</el-button>
              <el-button v-hasPermi="['channel:carPricingStandard:forbidden']" type="text" @click="forbidden(scope.row)" v-if="scope.row.enableStatus ==1">禁用</el-button>
            </template>
          </el-table-column>
          <el-table-column label="级别" width="100" align="center">
            <template slot-scope="scope">
              <span :class="{'blue':scope.row.enableStatus ==1}">{{scope.row.alternativeCarLevelName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="维保替车费用(元)" align="center">
            <template slot-scope="scope">
              <span :class="{'blue':scope.row.enableStatus ==1}">{{scope.row.alternativeCarFee}}</span>
            </template>
          </el-table-column>
          <el-table-column label="限行替车费用(元)" align="center">
            <template slot-scope="scope">
              <span :class="{'blue':scope.row.enableStatus ==1}">{{scope.row.trafficRestrictionFee}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="form-pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" :page-sizes="[10, 20, 30, 50]" layout="total,  prev, pager, next,sizes, jumper" :total="total">
        </el-pagination>
      </div>
      <!-- 添加或修改测试单表对话框 -->
      <el-dialog :title="title" :visible.sync="open" append-to-body class="form-dialog" width="40%">
        <div style="width: 70%; margin: 0 auto;">

          <el-form ref="form" :model="form" label-width="180px" :rules="rules">
            <el-form-item label="级别:" prop="alternativeCarLevelId">
              <el-select v-model="form.alternativeCarLevelId" clearable>
                <template v-for="dict in levelList">
                  <el-option :label="dict.level" :value="dict.id" :key="dict.id"></el-option>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="维保替车费用(元):" prop="alternativeCarFee">
              <el-input v-model="form.alternativeCarFee" maxlength="13" clearable @input="form.alternativeCarFee=form.alternativeCarFee.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"></el-input>
            </el-form-item>
            <el-form-item label="限行替车费用(元):" prop="trafficRestrictionFee">
              <el-input v-model="form.trafficRestrictionFee" maxlength="13" clearable @input="form.trafficRestrictionFee=form.trafficRestrictionFee.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"></el-input>
            </el-form-item>
            <el-form-item label="其他城市:">
            </el-form-item>
            <div style="display: flex;justify-content: start;">
              <el-table :data="tableData">
                <el-table-column label="城市">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.cityIds" multiple filterable>
                      <template v-for="item in scope.row.cityList">
                        <el-option :label="item.regionName" :value="item.regionId" :key="item.regionId"></el-option>
                      </template>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="维保替车费用(元)">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.alternativeCarFee" maxlength="13" @input="scope.row.alternativeCarFee=scope.row.alternativeCarFee.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" placeholder="请输入内容"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="" width="50">
                  <template slot-scope="scope">
                    <i class="el-icon-delete" @click="dele(scope,scope.row)"></i>
                  </template>
                </el-table-column>
              </el-table>
              <!-- <p style="display: flex;flex-wrap: wrap;justify-content: flex-end; align-items: center; width: 15px;border: 1px solid;">
              <i v-for="(item,i) in tableData" :key="i" class="el-icon-delete" style="height: 30px; border: 1px  solid red;"></i>
            </p> -->
            </div>

            <el-button type="info" plain size="mini" @click="addTable">增加<i class="el-icon-plus"></i></el-button>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button @click="cancel">取消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

  <script>
import SearchContent from "@/components/SearchContent/index.vue";
import {
  getCarList,
  onCarSave,
  onCarUpdate,
  onCarDelete,
  onCarSearch,
  getCarLevelList,
  updateEnableCarPricing,
} from "@/api/globalField";
import { regionList } from "@/api/system/dept.js";
export default {
  name: 'CarPricingStandard',

  components: {
    SearchContent,
  },
  dicts: ["enable_status"],
  data() {
    return {
      levelList: [],
      rules: {
        alternativeCarLevelId: [
          { required: true, message: "请选择级别", trigger: "change" },
        ],
        startMsrp: [
          { required: true, message: "请输入最低指导价", trigger: "change" },
        ],
        endMsrp: [
          { required: true, message: "请输入最高指导价", trigger: "change" },
        ],
        alternativeCarFee: [
          { required: true, message: "请输入维保替车费用", trigger: "change" },
        ],
        trafficRestrictionFee: [
          { required: true, message: "请输入限行替车费用", trigger: "change" },
        ],
      },
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      isNew: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dataList: [],
      // 表单参数
      form: {},
      tableData: [
        {
          cityIds: [],
          cityList: [],
          alternativeCarFee: null,
        },
      ],
      cityList: [],
      cityOtherList: [],
      mergeObj: {}, // 用来记录需要合并行的下标
      mergeArr: [
        // "id",
        // "alternativeCarFee",
        // "alternativeCarFeeEnd",
        // "alternativeCarLevelName",
        // "cityNames",
        // "trafficRestrictionFee",
      ], // 表格中的列名
    };
  },
  created() {
    this.getList();
    this.getCity();
    this.getCarLevelList();
  },
  methods: {
    forbidden(row) {
      let data = {
        id: row.id,
        enableStatus: 0,
      };
      this.$confirm("确认禁用?", "禁用", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateEnableCarPricing(data).then((res) => {
            this.$message({
              type: "success",
              message: "禁用成功",
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消禁用",
          });
        });
    },
    start(row) {
      let data = {
        id: row.id,
        enableStatus: 1,
      };
      this.$confirm("确认启用?", "启用", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateEnableCarPricing(data).then((res) => {
            this.$message({
              type: "success",
              message: "启用成功",
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消启用",
          });
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 导出
      this.download_json(
        "/setting/alternativeCarPricing/export",
        {
          alternativeCarLevelId: this.queryParams.alternativeCarLevelId,
          enableStatus: this.queryParams.enableStatus,
        },
        `替换车定价标准表_${new Date().getTime()}.xlsx`
      );
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // getSpanArr方法
    getSpanArr(data) {
      this.mergeArr.forEach((key, index1) => {
        let count = 0; // 用来记录需要合并行的起始位置
        this.mergeObj[key] = []; // 记录每一列的合并信息
        data.forEach((item, index) => {
          // index == 0表示数据为第一行，直接 push 一个 1
          if (index === 0) {
            this.mergeObj[key].push(1);
          } else {
            // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
            if (item[key] === data[index - 1][key]) {
              this.mergeObj[key][count] += 1;
              this.mergeObj[key].push(0);
            } else {
              // 如果当前行和上一行其值不相等
              count = index; // 记录当前位置
              this.mergeObj[key].push(1); // 重新push 一个 1
            }
          }
        });
      });
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 判断列的属性
      if (this.mergeArr.indexOf(column.property) !== -1) {
        // 判断其值是不是为0
        if (this.mergeObj[column.property][rowIndex]) {
          return [this.mergeObj[column.property][rowIndex], 1];
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    getCarLevelList() {
      getCarLevelList().then((res) => {
        console.log(res, "---");
        this.levelList = res.data;
      });
    },
    // 拆分数据数据
    splitData(data) {
      const result = [];
      data.forEach((row) => {
        const pricingLists = row.alternativeCarCityPricingList;
        pricingLists.forEach((pricingList, index) => {
          const newRow = {
            ...row,
            cityNames: pricingList.cityNames.join(),
            alternativeCarFeeEnd: pricingList.alternativeCarFee,
          };
          //   delete newRow.alternativeCarCityPricingList;
          //   delete newRow.alternativeCarLevelId;
          //   delete newRow.id;
          result.push(newRow);
        });
      });
      return result;
    },
    dele(row, rows) {
      console.log(rows.cityIds, this.cityOtherList);
      this.tableData.splice(row.$index, 1);
      //   单选
      //   this.cityOtherList.splice(row.$index, 1);
      // 多选
      this.cityOtherList = this.cityOtherList.filter(
        (item) => !rows.cityIds.includes(item)
      );
    },
    // 检查数组对象的值不能为空
    checkAllFieldsNotEmpty(array) {
      for (let i = 0; i < array.length; i++) {
        const obj = array[i];
        for (const key in obj) {
          if (obj.hasOwnProperty(key) && !obj[key]) {
            return false; // 如果任何一个字段为空，则返回false
          }
        }
      }
      return true; // 如果所有字段都不为空，则返回true
    },
    // 添加一行
    addTable() {
      const result = this.tableData.map((item) => {
        return {
          city: item.cityIds.join(","),
          alternativeCarFee: item.alternativeCarFee,
        };
      });
      let bol = this.checkAllFieldsNotEmpty(result);
      if (bol) {
        let cityOther = this.tableData.map((item) => {
          return item.cityIds;
        });
        this.cityOtherList.push(...cityOther);
        this.cityOtherList = [
          ...new Set(
            this.cityOtherList.reduce(
              (accumulator, current) => accumulator.concat(current),
              []
            )
          ),
        ];
        console.log(this.cityOtherList, "this.cityOtherList");
        let filteredArr = this.cityList.filter(
          (item) => !this.cityOtherList.includes(item.regionId)
        );
        this.tableData.push({
          cityIds: null,
          alternativeCarFee: null,
        });
        this.$set(
          this.tableData[this.tableData.length - 1],
          "cityList",
          filteredArr
        );
      } else {
        this.$message.error("请填写完整");
        return;
      }
    },
    getCity() {
      regionList({
        regionLevel: 2, //显示级别 1省 2省市 3省市区 ；为空默认3
        areaId: null, //区域id；为空默认全国
      }).then((res) => {
        let city = res.data.filter((item) => {
          return ![2].includes(item.regionLevel);
        });
        this.cityList = city;
        this.tableData &&
          this.tableData.forEach((item) => {
            item.cityList = city;
          });
      });
    },
    /** 查询测试单表列表 */
    getList() {
      this.loading = true;
      getCarList(this.queryParams).then((res) => {
        if (res.code == "200") {
          const { rows, total } = res;
          this.total = total;
          this.loading = false;
          this.dataList = rows

          // this.dataList = this.splitData(rows);
          // this.dataList && this.getSpanArr(this.dataList);
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.tableData = [
        {
          city: null,
          cityList: this.cityList,
          alternativeCarFee: null,
        },
      ];
      this.cityOtherList = [];
    },
    reset() {
      this.form = {
        includeStart: 0,
        includeEnd: 1,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      (this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      }),
        this.handleQuery();
    },
    /** 新增操作 */
    handleAdd() {
      this.open = true;
      this.title = "新增";
      this.$refs["form"] && this.$refs["form"].resetFields();
      this.reset();
    },
    /** 作废 */
    voidOth(row) {
      console.log("作废", row);
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row);
      this.open = true;
      this.title = "编辑";
      this.form = row;
      onCarSearch(row.id).then((res) => {
        this.form = res.data;
        this.tableData = res.data.alternativeCarCityPricingList;
        this.tableData.forEach((item) => {
          item.cityList = this.cityList;
        });
      });
    },

    /** 提交按钮 */
    submitForm() {
      console.log(this.tableData, "this.tableData");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.alternativeCarCityPricingList = this.tableData;
          if (this.title == "新增") {
            onCarSave(this.form).then((res) => {
              this.cancel();
              this.getList();
              this.$message.success("新增成功");
            });
          } else {
            // 调取接口
            onCarUpdate(this.form).then((res) => {
              this.cancel();
              this.getList();
              this.$message.success("编辑成功");
            });
          }
        }
      });
    },
  },
};
</script>


  <style lang="scss" scoped>
.pagination-container {
  padding: 0 20px 50px !important;
}
.form-pagination {
  text-align: right;
  margin-top: 20px;
}
.form-dialog {
  ::v-deep .el-dialog__header {
    padding: 10px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-dialog__headerbtn {
      top: 15px;
    }
  }

  .box-card {
    margin-bottom: 20px;

    .card-title {
      font-size: 16px;
      position: relative;
      margin-left: 8px;
      padding: 0;
    }

    .card-title::after {
      content: "";
      width: 4px;
      height: 18px;
      background-color: aqua;
      display: block;
      position: absolute;
      left: -12px;
      top: 2px;
    }
  }
}
.text {
  color: #606266 !important;
}
.blue {
  color: #1890ff !important;
}
</style>
